package swu.cx.retrofittest

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.core.net.toUri
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.net.HttpURLConnection

class MainActivity : AppCompatActivity() {
   private val retrofit = Retrofit.Builder()
        .baseUrl("http://192.168.0.103/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
   private val api = retrofit.create(NetWorkAPI::class.java)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       button1.setOnClickListener {
           NormalGet()
       }
        button2.setOnClickListener {
            hasParamsGet()
        }
        button3.setOnClickListener {
            MultyParamsGetLogin()
        }
        button4.setOnClickListener {
            PostParamsLogin()
        }
        button5.setOnClickListener {
            applyForMemoryJurisdiction()
        }
        button6.setOnClickListener {
            downLoadFile()
        }
        button7.setOnClickListener {
            getDynamicWeather()
        }
    }
    fun NormalGet(){

        val call = api.getJsonTestString()
        call.enqueue(object :Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                showText.text = response.body()?.string()
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.v("cx","失败")
            }

        })
    }
    fun hasParamsGet(){
        val retrofit = Retrofit.Builder()
            .baseUrl("http://apis.juhe.cn/simpleWeather/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val api = retrofit.create(NetWorkAPI::class.java)
        val call = api.getWeather("北京")
        call.enqueue(object :Callback<Weather>{
            override fun onResponse(call: Call<Weather>, response: Response<Weather>) {
                val cityName = response.body()?.result?.city
                showText.text = "当前城市：$cityName"
            }

            override fun onFailure(call: Call<Weather>, t: Throwable) {
            }

        })
    }
    fun getDynamicWeather(){
        val url = "http://apis.juhe.cn/simpleWeather/query?city=北京&key=c68586aea770073872b1778e3698efbc"
        val call = api.dynamicGetWeather(url)
        call.enqueue(object:Callback<Weather>{
            override fun onResponse(call: Call<Weather>, response: Response<Weather>) {
                val cityName = response.body()?.result?.city
                showText.text = "动态URL获取当前城市：$cityName"
            }

            override fun onFailure(call: Call<Weather>, t: Throwable) {
            }
        })
    }
    fun MultyParamsGetLogin(){
        val paramsMap = HashMap<String,String>().apply {
            put("user_name","jack")
            put("user_pwd","123")
        }
        val call = api.getMultyParamsLogin(paramsMap)
        call.enqueue(object :Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                showText.text = response.body()?.string()
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
            }
        })
    }
    fun PostParamsLogin(){
        val call = api.getPostFormLogin("jack","123")
        call.enqueue(object :Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                Toast.makeText(this@MainActivity,"登录成功！",Toast.LENGTH_SHORT).show()
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

            }

        })
    }
    fun applyForMemoryJurisdiction(){
        val filePath = Environment.getExternalStorageDirectory().absolutePath+"/a/retrofit.png"
        val file = File(filePath)
        if (Build.VERSION.SDK_INT >= 23) {
            val REQUEST_CODE_CONTACT = 101
            val permissions = arrayOf<String>(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            //验证是否许可权限
            for (str in permissions) {
                if (this.checkSelfPermission(str) !== PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT)
                    return
                } else {
                    postFile(file)
                }
            }
        }
    }
    fun postFile(file: File){
        val requestBodyFile = RequestBody.create(MediaType.parse("image/png"),file)
        val multyBody = MultipartBody.Part.createFormData("file","retrofit上传的文件.png",requestBodyFile )
        val call = api.getPostFile(multyBody)
        call.enqueue(object :Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                showText.text = response.body()?.string()
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
            }

        })
    }
    fun downLoadFile(){
        val call = api.getDownLoadPic()
        call.enqueue(object :Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                val filePath = Environment.getExternalStorageDirectory().absolutePath+"/a/retrofitDownload.png"
                val diskFile = File(filePath)
                if (!diskFile.exists()){
                    diskFile.createNewFile()
                }
                response.body()?.byteStream().use {input->
                    val buffer = input?.readBytes()
                    diskFile.outputStream().use {output->
                        output.write(buffer)
                    }
                   BitmapFactory.decodeFile(filePath).also { imageView.setImageBitmap(it) }
                }
            }
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

            }

        })
    }
}